<template>
  <view class="app bg">
    <view class="main-top">
      <image mode="aspectFit" src="@/static/image/login.svg" class="absolute banner w-full"></image>
      <image mode="aspectFit" :src="config.custom.login_logo" class="absolute logo w-full"></image>
    </view>
    <view class="main-body">
      <view class="input-item">
        <view class="input-title">手机号码</view>
        <view class="input-line">
          <input
            type="number"
            v-model="phone"
            placeholder="请输入手机号码"
            placeholder-class="input-placeholder"
          />
        </view>
      </view>

      <view class="input-item" v-if="loginType === 'phone'">
        <view class="input-title">验证码</view>
        <view class="input-line">
          <view class="flex flex-1 overflow-hidden" @click="openKeyborad()">
            <u-message-input
              mode="bottomLine"
              v-model="code"
              width="34"
              font-size="28"
              :maxlength="codeMaxlength"
              :breathe="false"
              :disabled-keyboard="true"
            ></u-message-input>
          </view>
          <u-keyboard
            mode="number"
            v-model="showKeyboard"
            :tooltip="false"
            :dot-enabled="false"
            @change="keyboardChange"
            @backspace="keyboardDelete"
          >
            <view class="paste-btn" @click="pasteCode()">粘贴</view>
          </u-keyboard>
          <view class="smscode-btn" :class="{ 'count-down': countActive }" @click="sendVerifyCode()">
            {{ showCodeText }}
          </view>
        </view>
      </view>

      <view class="input-item" v-if="loginType === 'password'">
        <view class="input-title">密码</view>
        <view class="input-line">
          <input
            type="password"
            v-model="password"
            placeholder="请输入密码"
            placeholder-class="input-placeholder"
          />
        </view>
      </view>

      <view class="login-btn" @click="userLogin()">登录</view>
      <view class="not-login-btn" @click="gotoHome()">暂不登录</view>

      <view class="flex justify-evenly px-5 mt-10">
        <!-- 微信小程序登录 -->
        /* #ifdef MP-WEIXIN */
        <button class="btn-view bg-red" open-type="getPhoneNumber" @getphonenumber="getUserPhoneNumber">
          <u-icon name="auth" custom-prefix="mt-icon" size="55" class="icon auth-icon" color="white"></u-icon>
          <view class="icon-title">授权登录</view>
        </button>
        /* #endif */

        <!-- 验证码登录 -->
        <view class="flex flex-col items-center" v-if="loginType == 'password'" @click="loginType = 'phone'">
          <u-icon
            name="phone"
            custom-prefix="mt-icon"
            size="45"
            class="icon phone-icon"
            color="white"
          ></u-icon>
          <view class="icon-title">手机登录</view>
        </view>

        <!-- 密码登录 -->
        <view class="flex flex-col items-center" v-if="loginType == 'phone'" @click="loginType = 'password'">
          <u-icon
            name="key"
            custom-prefix="mt-icon"
            size="40"
            class="icon password-icon"
            color="white"
          ></u-icon>
          <view class="icon-title">密码登录</view>
        </view>
      </view>

      <view class="footer">
        <text @click="goto('/pages/auth/forget')">忘记密码</text>
        <text class="mx-35rpx">|</text>
        <text @click="goto('/pages/auth/register')">注册账户</text>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { onLoad } from '@dcloudio/uni-app';
  import { wxOauth } from '@/api/auth/index';
  import { h5OauthByCode, h5OauthByPassword, sendSmsCaptcha } from '@/api/auth';
  import { useFansStore } from '@/store/fans';
  import { report } from '@/utils/exception';
  import { msg } from '@/utils/msg';
  import { regexpPhone } from '@/utils/regexp';
  import { config } from '@/config/env';
  import { getUrlParams } from '@/utils/funclib';

  const fansStore = useFansStore();
  const loginType = ref<string>('password');
  const showKeyboard = ref<boolean>(false);
  const codeText = '获取验证码';
  const showCodeText = ref<string>(codeText);
  const countActive = ref<boolean>(false);
  const lifeTime = 60;
  let leftTime = lifeTime;
  let codeMaxlength = 6;
  let inviteCode = '';

  const phone = ref<string>('');
  const code = ref<string>('');
  const password = ref<string>('');

  onLoad((options: any) => {
    if (fansStore.fansinfo.token) {
      return uni.switchTab({ url: '/pages/index/index' });
    }

    if (options.q) {
      const url = decodeURIComponent(options.q);
      inviteCode = getUrlParams(url, 'code');
    }

    if (options['type']) {
      loginType.value = options['type'];
    }
  });

  const openKeyborad = () => {
    code.value = '';
    showKeyboard.value = true;
  };

  const keyboardChange = (val: string) => {
    if (code.value.length >= codeMaxlength) return;
    code.value += val;
    if (code.value.length == codeMaxlength) {
      showKeyboard.value = false;
      userLogin();
    }
  };

  const keyboardDelete = () => {
    if (!code.value.length) return;
    code.value = code.value.substring(0, code.value.length - 1);
  };

  const pasteCode = () => {
    uni.getClipboardData({
      success: (res) => {
        if (!/^\d{6}$/.test(res.data)) return;
        code.value = res.data;
        showKeyboard.value = false;
        userLogin();
      },
    });
  };

  const verifyPhone = () => {
    if (!phone.value) {
      msg.error('请输入手机号码');
      return false;
    }

    if (!regexpPhone(phone.value)) {
      msg.error('手机号码格式错误');
      return false;
    }
    return true;
  };

  const sendVerifyCode = () => {
    if (countActive.value) {
      return;
    }

    if (!verifyPhone()) {
      return;
    }

    // 后台发送验证码
    msg.loading('发送中');
    sendSmsCaptcha(phone.value, 'login')
      .then((res) => {
        setTimeout(() => {
          msg.success('验证码已发送');
          countActive.value = true;
          showCodeText.value = leftTime + 's';
          openKeyborad();

          let timer = setInterval(() => {
            if (leftTime == 0) {
              leftTime = lifeTime;
              showCodeText.value = codeText;
              countActive.value = false;
              clearInterval(timer);
              return;
            }

            leftTime--;
            showCodeText.value = leftTime + 's';
          }, 1000);
        }, 1000);
      })
      .catch((err) => {
        setTimeout(() => {
          report(err);
        }, 800);
      });
  };

  // 验证码 / 密码登录
  const userLogin = () => {
    if (!verifyPhone()) {
      return;
    }

    switch (loginType.value) {
      // 验证码登录
      case 'phone':
        if (!code.value) {
          return msg.error('请输入验证码');
        }

        msg.loading('正在登录');
        h5OauthByCode(phone.value, code.value)
          .then((res) => {
            msg.success('登录成功');
            fansStore.setFansInfo(res.data);
            setTimeout(() => {
              gotoHome();
            }, 1500);
          })
          .catch((err) => {
            report(err);
          });

        break;

      // 密码登录
      case 'password':
        if (!password.value) {
          return msg.error('请输入密码');
        }

        msg.loading('正在登录');
        h5OauthByPassword(phone.value, password.value)
          .then((res) => {
            msg.success('登录成功');
            fansStore.setFansInfo(res.data);
            setTimeout(() => {
              gotoHome();
            }, 1500);
          })
          .catch((err) => {
            report(err);
          });
        break;
      default:
        msg.error('暂不支持该登录方式');
        return;
    }
  };

  // 微信小程序授权登录
  const getUserPhoneNumber = (e: any) => {
    if (e.detail.errno && e.detail.errno === 1400001) {
      return msg.error('请通知管理员充值额度');
    }

    if (e.detail.errMsg != 'getPhoneNumber:ok') {
      return msg.error('请授权您的手机号码登录', 2500);
    }

    const phoneCode = e.detail.code;

    msg.loading('授权中');
    uni.login({
      provider: 'weixin',
      success: (resLogin) => {
        if (resLogin.errMsg == 'login:ok') {
          const loginCode = resLogin.code;
          wxOauth(loginCode, phoneCode, inviteCode)
            .then((res) => {
              msg.success('登录成功', 1500);
              fansStore.setFansInfo(res.data);
              setTimeout(() => {
                gotoHome();
              }, 1500);
            })
            .catch((err) => {
              report(err);
            });
        }
      },
    });
  };

  const gotoHome = () => {
    uni.switchTab({ url: '/pages/index/index' });
  };

  const goto = (url: string) => {
    uni.navigateTo({ url: url });
  };
</script>

<style lang="scss" scoped>
  .bg {
    background: linear-gradient(315deg, #e8ebf8, #eef5f7);
  }

  .main-top {
    .banner {
      top: -230rpx;
    }

    .logo {
      top: 200rpx;
      height: 160rpx;
      margin: 0 auto;
    }
  }

  .main-body {
    background: white;
    margin: 52% 40rpx 10%;
    padding: 70rpx 40rpx 60rpx;
    border-radius: 30rpx;
    box-shadow: rgba(64, 64, 64, 0.1) 0px 20px 60px;

    .input-item {
      &:not(:last-child) {
        margin-bottom: 45rpx;
      }
      .input-title {
        font-size: 26rpx;
        font-weight: 600;
        color: #74848c;
        margin-left: 5rpx;
        margin-bottom: 18rpx;
      }

      .input-line {
        display: flex;
        align-items: center;
        background: #eef5f7;
        padding: 0 32rpx;
        height: 96rpx;
        border-radius: 20rpx;

        input {
          font-size: 28rpx;
          font-weight: 600;
          padding-left: 5rpx;
          letter-spacing: 2rpx;
          width: 100%;
        }

        .smscode-btn {
          color: #0851dd;
          font-size: 27rpx;
          width: 180rpx;
          text-align: center;
          margin-left: 20rpx;
          padding-left: 25rpx;
          border-left: 1rpx solid black;
        }

        .count-down {
          color: #8d8d8d;
        }
      }

      .paste-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100rpx;
        border-radius: 12rpx;
        padding: 12rpx 15rpx;
        margin: 12rpx 0 12rpx 30rpx;
        background: #f2f2f2;
      }
    }

    .login-btn,
    .not-login-btn {
      text-align: center;
      font-weight: 600;
      font-size: 27rpx;
      border-radius: 20rpx;
      padding: 27rpx 0;
    }
    .login-btn {
      color: white;
      letter-spacing: 8rpx;
      background: linear-gradient(315deg, #429ff6, #394eea, #2664ef);
      margin-bottom: 15rpx;
    }

    .not-login-btn {
      color: #8d8d8d;
      background: linear-gradient(315deg, #e7e7e7, #e8e9f7, #f5f5f5);
    }

    .icon {
      width: 100rpx;
      height: 100rpx;
      border-radius: 50%;
      display: flex;
      justify-content: center;
    }

    .auth-icon {
      background: #34d318;
    }

    .phone-icon {
      background: orange;
      margin-bottom: 16rpx;
    }

    .password-icon {
      background: #5135ce;
      margin-bottom: 16rpx;
    }

    .icon-title {
      color: gray;
      font-size: 25rpx;
      letter-spacing: 3rpx;
    }

    .footer {
      color: #b5b8b9;
      text-align: center;
      font-size: 27rpx;
      margin: 70rpx 0 10rpx;
      letter-spacing: 2rpx;
    }
  }

  :deep(.input-placeholder) {
    font-weight: 100;
  }
</style>
